package com.ben.multiple.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 树模型构建工具
 *
 * @author BenJin Yin
 * @date 2019/10/24
 */
public final class TreeUtils {
    private TreeUtils() {
    }

    /**
     * 构建树
     *
     * @param treeNodeList 所有树节点
     * @param root         根节点 id
     * @param <T>          树 类型
     * @return List<T>
     */
    public static <T extends TreeModel<T>> List<T> buildTree(List<T> treeNodeList, Object root) {
        List<T> treeList = new ArrayList<>();
        if (treeNodeList == null || treeNodeList.size() == 0) {
            return treeList;
        }
        if (root == null) {
            for (T treeNode : treeNodeList) {
                if (null == treeNode.getParentId()) {
                    treeList.add(findChildren(treeNode, treeNodeList));
                }
            }
        } else {
            for (T treeNode : treeNodeList) {
                if (root.equals(treeNode.getParentId())) {
                    treeList.add(findChildren(treeNode, treeNodeList));
                }
            }
        }
        return treeList;
    }

    /**
     * @param treeNode     树节点
     * @param treeNodeList 所有树节点
     * @param <T>          树类型
     * @return T
     */
    private static <T extends TreeModel<T>> T findChildren(T treeNode, List<T> treeNodeList) {
        for (T child : treeNodeList) {
            if (treeNode.getId().equals(child.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(child, treeNodeList));
            }
        }
        return treeNode;
    }

    public interface TreeModel<T extends TreeModel<?>> {

        Integer getId();

        Integer getParentId();

        List<T> getChildren();

        void setChildren(List<T> children);
    }
}
